/**
 * 员工模糊搜索
 */
import React from 'react';
import { Select, Spin } from 'antd';
import { useRequest } from '@/hooks';
import { getApplyEmployeeInfoList } from '@/services/components/userform';

const Employee = React.forwardRef(({ popupForBody, value, onChange, defaultInitData, ...rest }, ref) => {
    const { data = {}, loading, run } = useRequest(getApplyEmployeeInfoList, {
        debounceInterval: 500,
        manual: true
    });

    const handleSearch = _value => {
        // 注释原因：姓名输入匹配但不选中，再点击文本框则默认搜索只显示上次的搜索结果有误，应显示全部员工
        // if (_value) {
        run({
            employeeName: _value
        });
        // }
    };

    const { data: sourceData = [] } = data;
    const options = React.useMemo(() => {
        if (sourceData && sourceData.length > 0) {
            const tmpMap = {};
            return sourceData
                .filter(item => {
                    if (!tmpMap[item.employeeCode]) {
                        tmpMap[item.employeeCode] = 1;
                        return true;
                    }
                    return false;
                })
                .map(item => (
                    <Select.Option key={item.employeeCode} value={item.employeeCode}>
                        {item.employeeName}
                    </Select.Option>
                ));
        }
        return [];
    }, [sourceData]);

    React.useEffect(() => {
        if (defaultInitData) {
            run();
        }
    }, [defaultInitData]);

    return (
        <Spin spinning={loading}>
            <Select
                showSearch
                value={value}
                defaultActiveFirstOption={false}
                showArrow
                filterOption={false}
                allowClear
                onSearch={handleSearch}
                onChange={v => {
                    if (!v) run();
                    onChange(v);
                }}
                // onChange={onChange}
                notFoundContent={null}
                placeholder="请选择"
                getPopupContainer={triggerNode => (popupForBody ? document.body : triggerNode.parentElement)}
                ref={ref}
                {...rest}
            >
                {options}
            </Select>
        </Spin>
    );
});

export default Employee;
